<?php

namespace app\common\customer\model;

use app\common\config\logic\DictionaryLogic;
use app\common\config\model\ConfigCompany;
use app\common\config\model\ConfigStore;
use app\common\system\logic\UserLogic;
use think\model\concern\SoftDelete;

class CustomerInvite extends \think\Model
{
    protected $table = "tk_member_invite";
    use SoftDelete;
    protected $autoWriteTimestamp = true;
    protected $defaultSoftDelete = 0;

    protected $type = [
        'invite_time' => 'timestamp', // 邀约时间
        'visit_time' => 'timestamp', // 到店时间
    ];


    public function getMemberAttr($value, $data)
    {
        $model = new Customer();
        $row = $model->where('id', $data['member_id'])->field('id,fullname,source_id')->find();
        $row->append(['contact', 'source']);

        return $row;
    }

    // 分配人
    public function getCreatorAttr($value, $data)
    {
        $logic = new UserLogic();
        return $logic->getUser($data['create_id'], ['id', 'realname', 'status']);
    }

    // 接待人
    public function getUserAttr($value, $data)
    {
        $logic = new UserLogic();

        return $logic->getUser($data['user_id'], ['id', 'realname', 'status']);
    }

    public function getStoreAttr($value, $data)
    {
        // store_id may be 0
        if (!empty($data['store_id'])) {
            $logic = new DictionaryLogic();
            $store = $logic->getItem($data['store_id'], ConfigStore::class, ['id', 'title']);
            if (empty($store)) {
                $store = ['id' => 0, 'title' => $data['store_id']];
            }
        } else {
            $store = ['id' => 0, 'title' => ''];
        }

        return $store;
    }

    public function getVisitTimeAttr($value) {
        return empty($value) ? "" : date("Y-m-d", $value);
    }

    public function getCreateTimeAttr($value) {
        return empty($value) ? "" : date("Y-m-d", $value);
    }

    public function getInviteTimeAttr($value) {
        return empty($value) ? "" : date("Y-m-d", $value);
    }

    // 到店状态
    public function getStatusTextAttr($value, $data)
    {
        // 0待到店 1已到店 2已取消
        $statusMap = [
            0 => '待到店',
            1 => '已到店',
            2 => '已取消',
        ];
        return $statusMap[$data['status']];
    }

    //  品牌
    public function getBrandAttr($value, $data)
    {
        $logic = new DictionaryLogic();
        $brand = $logic->getItem($data['brand_id'], ConfigCompany::class, ['id', 'title']);

        if (empty($brand)) {
            $brand = ['id' => 0, 'title' => ''];
        }

        return $brand;
    }
}
